package org.jerrymouse.jsa4j.db.kv.gae.mem;

import org.jerrymouse.jsa4j.db.kv.DB;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

//import com.google.appengine.repackaged.org.apache.commons.logging.Log;
//import com.google.appengine.repackaged.org.apache.commons.logging.LogFactory;

/**
 * @author wuyang,kaiyannju
 */

public class GaeMemDB implements DB {

	// private static Log log = LogFactory.getLog(GaeDB.class);

	private DatastoreService datastore;

	private static String entityKind = "kvdb";
	private static String entityProperty = "value";

	public GaeMemDB(DatastoreService datastore) {
		this.datastore = datastore;
	}

	@Override
	public String get(String key) {
		Entity entity = gaeGet(key);
		if (entity == null) {
			return null;
		}
		return entity.getProperty(entityProperty).toString();
	}

	@Override
	public String put(String key, String value) {
		if (key == null) {
			return null;
		} else {
			Entity entity = gaeGet(key);
			if (entity == null) {
				if (value == null) {
					// log.info("key-value null value null.");
					return null;
				} else {
					entity = new Entity(KeyFactory.createKey(entityKind, key));
					entity.setProperty(entityProperty, value);
					datastore.put(entity);
					return null;
				}
			} else {
				if (value == null) {
					datastore.delete(KeyFactory.stringToKey(key));
					return null;
				} else {
					entity.setProperty(entityProperty, value);
					datastore.put(entity);
					return null;
				}
			}
		}
	}

	private Entity gaeGet(String key) {
		if (key == null) {
			// log.info("key null");
			return null;
		}

		Key gaeKey = null;
		try {
			gaeKey = KeyFactory.createKey(entityKind, key);
		} catch (IllegalArgumentException e) {
			// log.info(e);
			return null;
		}
		Entity entity = null;
		try {
			entity = datastore.get(gaeKey);
		} catch (EntityNotFoundException e) {
			// log.info(e);
			return null;
		}
		return entity;
	}

}
